﻿using Common.Logging;
using Dubbo.Common.Container;
using Dubbo.Common.Utils;
using Dubbo.Config.Spring.Schema;
using Spring.Context.Support;
using Spring.Objects.Factory.Xml;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Dubbo.Container.Spring
{
    [Export(typeof(IContainer))]
    [ExportMetadata("Name", "spring")]
    public class SpringContainer : IContainer
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(SpringContainer));

        public const string SPRING_CONFIG = "dubbo.spring.config";
    
        public const string DEFAULT_SPRING_CONFIG = "./spring/*.xml";
        
        private static XmlApplicationContext context;

        public static XmlApplicationContext GetContext()
        {
            return context;
        }

        public void Start()
        {
            NamespaceParserRegistry.RegisterParser(typeof(DubboNamespaceHandler));
            string configPath = ConfigUtils.Get(SPRING_CONFIG, DEFAULT_SPRING_CONFIG);
            context = new XmlApplicationContext(Regex.Split(configPath, "[,\\s]+"));
            context.Start();
        }

        public void Stop()
        {
            try
            {
                if (context != null)
                {
                    context.Stop();
                    context.Dispose();
                    context = null;
                }
            }
            catch (Exception e)
            {
                logger.Error(e.Message, e);
            }
        }

    }
}
